﻿using System;
using System.Text;
using Enyim.Caching;
using System.Web.Mvc;
using SilenthinkContract;
using System.Web.Security;
using SilenthinkContract.Domain;
using SilenthinkCommon.Extension;
using SilenthinkContract.Component;
using System.Web.Script.Serialization;
using SilenthinkCommon.Components;

namespace Web.Areas.Passport.Controllers
{
    public class HomeController : PassportBaseController
    {
        private const string LoginSessionKey = "login.session.key";
        private const string ForgotPasswordSessionKey = "forgotpassword.session.key";


        public HomeController(ILogService logService, IBaseService baseService, IExtraService extraService, IStoreService storeService, IOrderService orderService, IGameService gameService, IAuctionService auctionService, IPassportService passportService, IPaymentService paymentService, IMemcachedClient memcachedClient) : base(logService, baseService, extraService, storeService, orderService, gameService, auctionService, passportService, paymentService, memcachedClient)
        {
        }

        public ActionResult Index(string redirect)
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(string username, string password, string captcha, bool remember = false, string redirect = null)
        {
            var result = new SkResult<string>();
            if (!ValidateCaptcha(LoginSessionKey, captcha))
            {
                result.Message = "请输入正确的验证码！";
                return Json(result);
            }
            var pwd = (password.ToPassword() + PasswordSalt).ToPassword();
            var user = PassportService.GetUser(username, pwd);
            if (user != null)
            {
                var identity = new SilenthinkIdentity(user.Id, user.NickName, user.Role, string.Empty);
                SetAuthCookie(user.Name, remember, identity);
                result.Status = true;
                result.Extra = redirect;
                result.Data = user.NickName;
            }
            else
            {
                result.Message = "用户名或密码不正确！";
            }
            return Json(result);
        }

        public ActionResult SignOut(string redirect)
        {
            FormsAuthentication.SignOut();
            return Redirect(!string.IsNullOrEmpty(redirect) ? redirect : WebSite.Main);
        }

        public ActionResult Captcha()
        {
            return Captcha(LoginSessionKey);
        }

        public ActionResult ForgotPasswordCaptcha()
        {
            return Captcha(ForgotPasswordSessionKey);
        }

        public ActionResult SignIn(int? param = null)
        {
            return PartialView(param);
        }

        /// <summary>
        /// 找回密码
        /// </summary>
        /// <returns></returns>
        public ActionResult ForgotPassword()
        {
            return View();
        }

        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="param">1为通过注册邮箱，2为通过绑定手机号码</param>
        /// <param name="email">电子邮箱</param>
        /// <param name="mobile">手机号</param>
        /// <param name="smscode">短信验证码</param>
        /// <param name="captcha">验证码</param>
        /// <param name="password"></param>
        /// <param name="confirmPassword"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ResetPassword(int param = 1, string email = null, string mobile = null, string smscode = null, string captcha = null, string password = null, string confirmPassword = null)
        {
            var guid = Guid.NewGuid();
            var result = new SkResult<string>();
            if (param == 1)
            {
                if (!email.IsEmail())
                {
                    result.Message = "请输入正确的电子邮箱地址！";
                    return Json(result);
                }
                if (!ValidateCaptcha(ForgotPasswordSessionKey, captcha))
                {
                    result.Message = "请输入正确的验证码！";
                    return Json(result);
                }
                if (!PassportService.ExistUserName(email))
                {
                    result.Message = "不存在该电子邮箱！";
                    return Json(result);
                }
                else
                {
                    //todo 发送邮件
                    var log = new EmailVerification();
                    var authCode = email.AesEncrypt(AesKey);
                    log.Id = guid;

                    log.Email = email;
                    log.Category = 1;
                    log.AuthCode = authCode;
                    log.CreatedBy = "sys.resetpwd";
                    log.CreatedOn = DateTime.Now;
                    var status = ExtraService.CreateEmailVerification(log);
                    if (status)
                    {
                        result.Status = true;
                    }
                    else
                    {
                        result.Message = "发送邮件失败！";
                    }
                    //return Json(result);
                }
            }
            if (param == 2)
            {
                if (!mobile.IsMobile() || smscode.IsNullOrEmpty())
                {
                    result.Message = "请输入正确的手机号码和短信验证码！";
                    return Json(result);
                }
                if (password.IsNullOrEmpty() || confirmPassword.IsNullOrEmpty())
                {
                    result.Message = "请输入新密码！";
                    return Json(result);
                }
                if (password != confirmPassword)
                {
                    result.Message = "两次输入的密码不一致！";
                    return Json(result);
                }

                var log = ExtraService.GetSmsVerification(smscode, mobile);
                if (log != null && mobile == log.Mobile)
                {
                    var user = PassportService.GetUser(log.UserId);
                    var newPassword = (password.ToPassword() + PasswordSalt).ToPassword();
                    var status = PassportService.ChangePassword(user.Id, newPassword);
                    if (status)
                    {
                        result.Status = true;
                    }
                    else
                    {
                        result.Message = "更新密码失败！";
                    }
                }
                else
                {
                    result.Message = "手机号码不正确或短信验证码已过期！";
                }

            }
            else
            {
                result.Message = "参数不正确！";
            }
            return Json(result);
        }
        /// <summary>
        /// 通过注册邮箱重新设置密码
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public ActionResult ResetPasswordByEmail(string param)
        {
            var result = new SkResult<string>();

            var data = ExtraService.GetEmailVerification(param, 1);
            if (data != null)
            {
                if (data.Email == data.AuthCode.AesDecrypt(AesKey))
                {
                    result.Status = true;
                    result.Data = data.Email;
                    result.Message = param;
                }
            }
            else
            {
                result.Message = "参数不正确或该链接已失效！";
            }

            return View(result);
        }
        [HttpPost]
        public ActionResult ResetPasswordByEmail(string param, string password, string confirmPassword)
        {
            var result = new SkResult<string>();
            if (password != confirmPassword)
            {
                result.Message = "两次输入的密码不一致!";
                return Json(result);
            }
            var data = ExtraService.GetEmailVerification(param, 1);
            if (data != null)
            {
                if (data.Email == data.AuthCode.AesDecrypt(AesKey))
                {
                    var user = PassportService.GetUser(data.Email);
                    var newPassword = (password.ToPassword() + PasswordSalt).ToPassword();
                    var status = PassportService.ChangePassword(user.Id, newPassword);
                    if (status)
                    {
                        result.Status = true;
                    }
                    else
                    {
                        result.Message = "更新密码失败！";
                    }
                }
            }
            else
            {
                result.Message = "参数不正确！";
            }
            return Json(result);
        }
        [HttpPost]
        public ActionResult SmsCode(int param = 0, string mobile = null)
        {
            var result = new SkResult<string>();
            if (param >= 0 && !mobile.IsNullOrEmpty())
            {
                if (param == 0)
                {
                    result = GetRegisterSmsCode(mobile);
                }
                else if (param == 1)
                {
                    result = GetResetPasswordSmsCode(mobile);
                }
            }
            else
            {
                result.Message = "参数不正确！";
            }
            return Json(result);
        }

        private SkResult<string> GetRegisterSmsCode(string mobile)
        {
            var guid = Guid.NewGuid();
            var result = new SkResult<string>();
            if (mobile.IsMobile())
            {
                var exists = PassportService.ExistUserName(mobile);
                if (!exists)
                {
                    var log = new SmsVerification();
                    var bytes = Utility.GenerateRandomNumber(3);
                    log.Id = guid;
                    log.UserId = 0;
                    log.Category = 0;
                    log.Mobile = mobile;
                    log.SmsCode = bytes.ToHex();
                    log.CreatedBy = "sys.register";
                    log.CreatedOn = DateTime.Now;
                    var status = ExtraService.CreateSmsVerification(log);
                    if (status)
                    {
                        result.Status = true;
                    }
                    else
                    {
                        result.Message = "发送手机验证失败，请重试！";
                    }
                }
                else
                {
                    result.Message = "该手机号码已注册！";
                }
            }
            else
            {
                result.Message = "请输入正确的手机号码！";
            }
            return result;
        }
        private SkResult<string> GetResetPasswordSmsCode(string mobile)
        {
            var guid = Guid.NewGuid();
            var result = new SkResult<string>();
            if (mobile.IsMobile())
            {
                var user = PassportService.GetUserByMobile(mobile);
                if (user != null && !user.Mobile.IsNullOrEmpty())
                {
                    var log = new SmsVerification();
                    var bytes = Utility.GenerateRandomNumber(3);
                    log.Id = guid;
                    log.UserId = user.Id;
                    log.Category = 1;
                    log.Mobile = mobile;
                    log.SmsCode = bytes.ToHex();
                    log.CreatedBy = "sys.resetpwd";
                    log.CreatedOn = DateTime.Now;
                    var status = ExtraService.CreateSmsVerification(log);
                    if (status)
                    {
                        result.Status = true;
                    }
                    else
                    {
                        result.Message = "发送手机验证码失败，请重试！";
                    }
                }
                else
                {
                    result.Message = "该手机号码不存在或未绑定任何帐号！";
                }
            }
            else
            {
                result.Message = "请输入正确的手机号码！";
            }
            return result;
        }

        public ActionResult Me()
        {
            var sb = new StringBuilder();
            sb.Append("Sk.CurrentUser={");
            sb.AppendFormat("IsAuthenticated:{0},", User.Identity.IsAuthenticated.ToString().ToLower());
            sb.AppendFormat("NickName:'{0}'", User.Identity.SkIdentity().NickName);
            sb.Append("};");
            return JavaScript(sb.ToString());
        }

        private void SetAuthCookie(string userName, bool createPersistentCookie, SilenthinkIdentity identity)
        {
            var userData = new JavaScriptSerializer().Serialize(identity);
            var authCookie = FormsAuthentication.GetAuthCookie(userName, createPersistentCookie);
            var ticket = FormsAuthentication.Decrypt(authCookie.Value);
            var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userData);
            authCookie.Value = FormsAuthentication.Encrypt(newTicket);
            if (createPersistentCookie)
            {
                authCookie.Expires = DateTime.Now.AddDays(14);
            }
            Response.Cookies.Add(authCookie);
        }

    }
}
